class Solution:
    def myAtoi(self, s: str) -> int:
        # 处理前导空格
        i = 0
        n = len(s)
        while i < n and s[i] == ' ':
            i += 1

        # 处理符号
        sign = 1
        if i < n and s[i] in '+-':
            if s[i] == '-':
                sign = -1
            i += 1

        # 处理前导零
        while i < n and s[i] == '0':
            i += 1

        # 收集数字字符
        digits = []
        while i < n and s[i].isdigit():
            digits.append(s[i])
            i += 1

        if not digits:
            return 0

        # 确定溢出边界
        if sign == 1:
            upper_bound = 2 ** 31 - 1
        else:
            upper_bound = 2 ** 31

        max_div10 = upper_bound // 10
        max_mod = upper_bound % 10

        abs_res = 0
        for c in digits:
            digit = int(c)
            if abs_res > max_div10 or (abs_res == max_div10 and digit > max_mod):
                return sign * upper_bound
            abs_res = abs_res * 10 + digit

        return sign * abs_res